package com.lhc.diy;

import com.lhc.web.dao.UserMapper;
import com.lhc.web.domain.UserDomain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author lhc
 * @Date 2020-09-25 9:39
 **/

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UserDomain userDomain = this.selectUserByName(userName);
        if (userDomain == null) {
            return null;
        }
        return this.buildMyUserDetails(userDomain);
    }

    /**
     * 根据账号查询用户
     *
     * @param userName 用户名
     * @return 数据库用户信息
     */
    private UserDomain selectUserByName(String userName) {
        UserDomain search = new UserDomain();
        search.setUserName(userName);
        return userMapper.selectOne(search);
    }

    /**
     * 查询用户权限 这边先搞个角色玩玩
     *
     * @param userId 用户id
     * @return 用户权限
     */
    private List<GrantedAuthority> selectUserPermissions(String userId) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        //用户角色
//        List<String> roleList = userMapper.userPermissions(userId);
        List<String> roleList = new ArrayList<>();
        roleList.add("p1");
        for (String role : roleList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role);
            authorities.add(simpleGrantedAuthority);
        }
        return authorities;
    }

    /**
     * 构建自定义返回的用户信息
     *
     * @param userDomain 数据库查询的userDomain
     * @return 自定义用户信息 继承userDetails
     */
    private MyUserDetails buildMyUserDetails(UserDomain userDomain) {
        MyUserDetails myUserDetails = new MyUserDetails();
        myUserDetails.setId(userDomain.getId());
        myUserDetails.setUsername(userDomain.getUserName());
        myUserDetails.setPassword(userDomain.getUserPassword());
        myUserDetails.setAuthorities(selectUserPermissions(userDomain.getId()));
        return myUserDetails;
    }
}